<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总共: {{ total }} 条</span>
        </template>

        <template #right>
          <el-button size="small" type="warning" @click="exportExcel"> 导出 Excel </el-button>
          <el-button size="small" type="danger" @click="$router.push('/employees/updateExcel')"> 导入 Excel </el-button>
          <el-button size="small" type="primary" @click="showDialog = true"> 新增员工 </el-button>
        </template>
      </page-tools>
      <!-- 具体页面结构 -->
      员工管理
      <el-card style="margin-top:'20px">
        <el-table :data="employees">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template v-slot="{ row }">
              <!-- <img class="avarat" :src="row.staffPhoto" alt=""> -->
              <image-holder :src="row.staffPhoto" />
            </template>
          </el-table-column>

          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用方式">
            <template v-slot="{ row }">
              <!-- {{ hireTypeMap[row.formOfEmployment] || '未知' }} -->
              {{ formatEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column sortable label="入职时间">
            <template v-slot="{ row }">
              {{ resetTime(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-button type="text" size="small" @click="$router.push('/employees/detail/?id=' + row.id)"> 查看 </el-button>
              <el-button type="text" size="small" @click="hAssign(row.id)"> 分配角色 </el-button>
              <el-button type="text" size="small" @click="hDel(row)"> 删除 </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :current-page="q.page"
          :page-sizes="[3, 5, 10, 20,1000]"
          :page-size="q.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
      <el-dialog
        title="新增员工"
        :visible.sync="showDialog"
        width="30%"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        @closed="hClosed"
      >
        <addDialog ref="reform" @success="hSuccess" @close="closeDialog" />
      </el-dialog>
      <el-dialog
        title="分配角色"
        :visible.sync="showDialogRole"
        width="40%"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        @closed="$refs.assignRole.resetRoles()"
      >
        <assign-role :id="curId" ref="assignRole" @close="showDialogRole= false" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { delEmployee, getEmployeeList } from '@/api/employees '
import addDialog from './empDialog.vue'
import employeesConst from '@/constant/employees'
import AssignRole from './assignRole.vue'
import dayjs from 'dayjs'
// import employees from '@/constant/employees'
const hireTypeMap = {}

employeesConst.hireType.forEach(item => {
  hireTypeMap[item.id] = item.value
})
export default {
  components: {
    addDialog,
    AssignRole
  },
  data() {
    return {
      q: {
        page: 1,
        size: 3
      },
      employees: [],
      total: 0,
      // hireTypeMap: {}
      showDialog: false,
      showDialogRole: false,
      curId: ''
    }
  },
  created() {
    this.loadEmployees()
    // employeesConst.hireType.forEach(item => {
    //   this.hireTypeMap[item.id] = item.value
    // })
  },
  methods: {
    async loadEmployees() {
      try {
        const res = await getEmployeeList(this.q)
        // console.log(res)
        this.total = res.data.total
        this.employees = res.data.rows
      } catch (e) {
        console.log(e)
      }
    },
    formatEmployment(code) { // code === 1  code === 2
    //   // 去常量中找到对应的中文并返回
    //   const result = employeesConst.hireType.find(item => item.id === code)
    //   // return result.value
    //   // 提高代码的健壮性
    //   if (result) {
      // return result.value
    //   } else {
    //     return '未知'
    //   }
      return hireTypeMap[code]
    },
    handleSizeChange(val) {
      this.q.size = val
      // console.log(val)
      this.loadEmployees()
    },
    handleCurrentChange(val) {
      // console.log(val)
      this.q.page = val
      this.loadEmployees()
    },
    async doDel(id) {
      const result = await this.$confirm('你确定要删除改员工的信息吗？嘿嘿嘿', '提示', {
        type: 'warning',
        closeOnClickModal: false,
        closeOnPressEscape: false
      }).catch(e => e)
      // console.log(result)
      if (result === 'cancel') return
      try {
        // console.log(row)
        const res = await delEmployee(id)
        // console.log(res)
        this.$message.success(res.message)
        if (this.total % this.q.size === 1) {
          this.q.page--
        }
        // console.log(this.q.page)
        this.loadEmployees()
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    hDel(row) {
      this.doDel(row.id)
    },
    closeDialog() {
      this.showDialog = false
    },
    hSuccess() {
      this.showDialog = false
      this.total++
      this.q.page = Math.ceil(this.total / this.q.size)
      this.loadEmployees()
    },
    resetTime(time) {
      // console.log(time)
      return dayjs(time).format('YYYY-MM-DD')
    },
    hClosed() {
      this.$refs.reform.resetForm()
    },
    exportExcel() {
      import('@/vendor/Export2Excel').then(async excel => {
        // console.log(excel)
        const res = await getEmployeeList({ page: 1, size: this.total })
        // console.log(res)
        const list = res.data.rows
        // this.formatDate(list)
        // console.log(header, data)
        const { header, data } = this.formatDate(list)
        excel.export_json_to_excel({

          header: header,
          data: data,
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类
        })
      })
    },
    formatDate(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const hireTypEnmu = {
        1: '正式',
        2: '非正式'
      }
      // console.log(list)
      let header = []
      let data = []
      const information = list[0]
      // console.log(list[0])
      // 这里判断list有没有数据， 如果没有数据，就直接返回空的header data
      if (!information) {
        return { header, data }
      }
      // Object.keys()获得information对象上所有的健，并且对他进行map遍历，key代表每一个健，然后通过map的映射关系，把mapInfo对应的映射的值返回，达到英文字符串转换成文字
      header = Object.keys(information).map(key => {
        return mapInfo[key]
      })
      // console.log(header)
      data = list.map(item => {
        const hireForm = item['formOfEmployment']
        // console.log(hireForm)
        item['formOfEmployment'] = hireTypEnmu[hireForm]
        // Object.values方法返回一个数组，成员是参数对象自身的（不含继承的）所有可遍历（ enumerable ）属性的键值。
        return Object.values(item)
      })
      // console.log(data)
      return { header, data }
    },
    hAssign(id) {
      // console.log(id)
      this.curId = id
      this.showDialogRole = true
      this.$nextTick(() => {
        this.$refs.assignRole.loadRoleIds()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  .avarat{
    width: 50px;
    height: 50px;
  }
</style>
